package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.mallcai.bigdata.ladon.dpl.vo.QueryFieldType;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryParamHolder;
import com.mallcai.bigdata.ladon.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mallcai.bigdata.ladon.service.report.impl.ReportQueryConstants.PARAM_NAME_FORMAT;

/**
 * 用来替换orderBy参数
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 11:08
 */
@Slf4j
@Service
@Order(5500)
public class ReplaceOrderByParamHandler extends AbstractReportQueryPreHandler {


    @Override
    public void preInternal(ReportQueryContext context) {
        Map<String, ReportQueryParamHolder> queryParams = context.getQueryParams();
        List<ReportQueryParamHolder> orderByFieldList = queryParams.values().stream()
                .filter(paramHolder -> QueryFieldType.contains(paramHolder.getQueryFieldType(), QueryFieldType.ORDER_BY))
                .collect(Collectors.toList());
         if (CollectionUtils.isNotEmpty(orderByFieldList)){
            String sql = context.getSql();
            String temp = sql;
            for(ReportQueryParamHolder reportQueryParamHolder : orderByFieldList){
                temp = temp.replaceAll(String.format(PARAM_NAME_FORMAT, reportQueryParamHolder.getName()),
                        String.valueOf(reportQueryParamHolder.getValue()));
            }
            context.setSql(temp);
            log.debug("替换前的sql:{},\n 替换后的sql:{}",sql, temp);
        }
    }

}
